import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution8 {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * 
     * @param head1 ListNode类 
     * @param head2 ListNode类 
     * @return ListNode类
     */
    public ListNode addInList (ListNode head1, ListNode head2) {
        // write code here
        head1 = reverse(head1);
        head2 = reverse(head2);
        int flg = 0;
        ListNode root = new ListNode(0);
        ListNode cur = root;
        while(head1 != null && head2 != null){
            int val = head1.val + head2.val + flg;
            flg = val / 10;
            cur.next = new ListNode(val % 10);
            cur = cur.next;
            head1 = head1.next;
            head2 = head2.next;
        }
        
        while(head1 != null){
                int val = (head1.val + flg);
                flg = val / 10;
                cur.next = new ListNode(val % 10);
                cur = cur.next;
                head1 = head1.next;
        }
        while(head2 != null){
                int val = (head2.val + flg);
                flg = val / 10;
                cur.next = new ListNode(val % 10);
                cur = cur.next;
                head2 = head2.next;
        }
        if(flg != 0){
            cur.next = new ListNode(flg);

        }
        return reverse(root.next);
    }
    public ListNode reverse(ListNode head){
        ListNode pre = null;
        while(head != null){
            ListNode Next = head.next;
            head.next = pre;
            pre = head;
            head = Next;
        }
        return pre;
    }
}